<template>
  <div class="container mx-auto py-8">
    <div class="flex gap-8">
      <!-- 左侧产品图片 -->
      <div class="w-1/6">
        <div class="top-4">
          <div class="bg-white rounded-lg shadow-md p-4">
            <!-- 主图 -->
            <div class="mb-4">
              <img v-for="(image, index) in product.PicUrls" :key="index" :src="image" :alt="product.name" class="w-full h-auto rounded-lg">
            </div>
            <!-- 缩略图列表 -->
            <!-- <div class="grid grid-cols-4 gap-2">
              <div 
                v-for="(image, index) in product.images" 
                :key="index"
                @click="selectedImage = image"
                class="cursor-pointer rounded-md overflow-hidden border-2 transition-all"
                :class="selectedImage === image ? 'border-primary' : 'border-transparent'"
              >
                <img 
                  :src="image" 
                  :alt="`${product.name}-${index}`"
                  class="w-full h-full object-cover"
                >
              </div>
            </div> -->
          </div>
        </div>
      </div>

      <!-- 中间产品信息 -->
      <div class="w-3/6">
        <h1 class="text-2xl font-bold mb-4">{{ product.name }}</h1>
        <div class="space-y-6">
          <!-- 价格信息 -->
          <!-- <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-3xl text-primary font-bold">
              ¥{{ product.price }}
            </div>
            <div class="text-gray-500 text-sm mt-1">
              市场参考价：<del>¥{{ product.originalPrice }}</del>
            </div>
          </div> -->

          <!-- 基本信息 -->
          <div class="space-y-4">
            <div class="flex items-center text-gray-600">
              <span class="">Manufacturer：</span>
              <span>{{ product.MFG }}</span>
            </div>
            <div class="flex items-center text-gray-600">
              <span class="">Datasheet：</span>
              <a class="text-blue-400 underline cursor-pointer" @click="handlePdf">{{ product.PdfName }}</a>
            </div>
            <div class="flex items-center text-gray-600">
              <span class="">Selling Point：{{ product.SellingPoints }}</span>
            </div>
            <!-- <div class="flex items-center text-gray-600">
              <span class="w-20">库存：</span>
              <span>{{ product.stock }} 件</span>
            </div> -->
          </div>

          <!-- 产品描述 -->
          <!-- <div class="space-y-2">
            <h2 class="text-lg font-medium">产品描述</h2>
            <p class="text-gray-600 leading-relaxed">
              {{ product.description }}
            </p>
          </div> -->

        </div>
      </div>

      <!-- 右侧订单卡片 -->
      <div class="w-2/6">
        <div class="sticky top-4">
          <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-lg font-medium mb-4 mb-0">Request Quote</h2>
            <p class="text-xs text-slate-400 mb-4">Please send RFQ , your dedicated sales manager will respond immediately</p>
            <!-- 订单表单 -->
            <form class="space-y-4" @submit.prevent="handleSubmit">
              <!-- 联系信息 -->
              <div class="flex gap-4">
                <div class="w-1/2">
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Contact Name
                  </label>
                  <input 
                    type="text"
                    v-model="orderInfo.Name"
                    class="w-full px-3 py-2 border rounded-md focus:ring-primary focus:border-primary"
                    placeholder="Please input contact name"
                  >
                  <div v-if="errors.Name" class="text-red-500 text-sm mt-1">{{ errors.Name }}</div>
                </div>
                <div class="w-1/2">
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Business Email
                  </label>
                  <input 
                    type="email"
                    v-model="orderInfo.Email"
                    class="w-full px-3 py-2 border rounded-md focus:ring-primary focus:border-primary"
                    placeholder="Please input business email"
                  >
                  <div v-if="errors.Email" class="text-red-500 text-sm mt-1">{{ errors.Email }}</div>
                </div>
              </div>

              <div class="flex gap-4">
                <div class="w-1/2">
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Company Name
                  </label>
                  <input 
                    type="text"
                    v-model="orderInfo.Company"
                    class="w-full px-3 py-2 border rounded-md focus:ring-primary focus:border-primary"
                    placeholder="Please input company name"
                  >
                  <div v-if="errors.Company" class="text-red-500 text-sm mt-1">{{ errors.Company }}</div>
                </div>
                <div class="w-1/2">
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Country
                  </label>
                  <input 
                    type="text"
                    v-model="orderInfo.Country"
                    class="w-full px-3 py-2 border rounded-md focus:ring-primary focus:border-primary"
                    placeholder="Please input country"
                  >
                  <div v-if="errors.Country" class="text-red-500 text-sm mt-1">{{ errors.Country }}</div>
                </div>
              </div>
              
              <div class="flex gap-4">
                <div class="w-1/3">
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Quantity
                  </label>
                  <input 
                    type="number"
                    v-model="orderInfo.Quantity"
                    min="1"
                    class="w-full px-3 py-2 border rounded-md focus:ring-primary focus:border-primary"
                  >
                  <div v-if="errors.Quantity" class="text-red-500 text-sm mt-1">{{ errors.Quantity }}</div>
                </div>
                <div class="w-2/3 flex gap-4 items-end">
                  <button 
                    type="submit"
                    class="text-sm w-1/2 bg-primary text-white py-3 rounded-md hover:bg-opacity-90 transition-colors"
                  >
                    Quick RFQ
                  </button>
                  <button 
                    @click="AddRfqList"
                    type="button"
                    class="text-sm w-1/2 bg-white text-primary border border-solid border-blue-300 py-3 rounded-md hover:bg-opacity-90 transition-colors"
                  >
                    Add to RFQ list
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- 技术参数 -->
    <div class="space-y-2  border-t border-solid border-inherit mt-8 pt-8">
      <h2 class="text-lg font-medium">Specifications</h2>
      <div class="bg-white rounded-lg border">
        <div class="flex border-b last:border-b-0 bg-gray-200">
          <div class="flex w-1/2">
            <div class="w-1/3 p-3">Type</div>
            <div class="w-2/3 p-3">Parameter</div>
          </div>
        </div>
        <div class="flex flex-row border-b last:border-b-0 flex-wrap">
          <div 
            v-for="(spec, index) in product.PartNoAttributeModels" 
            :key="index"
            class="flex flex-row border-b last:border-b-0  w-1/2"
          >
            <div class="w-1/3 p-3 bg-gray-50">{{ spec.AttributeName }}</div>
            <div class="w-2/3 p-3">{{ spec.AttributeValue }}</div>
          </div>
        </div>
        
      </div>
    </div>


    <!-- 弹框组件 -->
    <div v-if="showSuccessModal" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
      <div class="bg-white rounded-lg p-6 w-96 text-center">
        <h3 class="text-lg font-semibold mb-4">提交成功</h3>
        <p class="text-gray-700 mb-6">您的 RFQ 请求已成功提交！</p>
        <button 
          @click="showSuccessModal = false"
          class="bg-primary text-white px-4 py-2 rounded-md hover:bg-opacity-90"
        >
          确定
        </button>
      </div>
    </div>
  </div>
  
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useNuxtApp } from '#app'
import { useRfqStore } from '@/store/rfqStore'
const rfq = useRfqStore()
const router = useRouter()
const route = useRoute()
const { $request } = useNuxtApp() // 获取 Axios 实例

// 模拟产品数据
const product = ref({
  id: 1,
  name: 'STM32F103C8T6',
  price: 12.80,
  originalPrice: 15.00,
  model: 'STM32F103C8T6',
  brand: 'ST',
  stock: 999,
  description: 'STM32F103C8T6是意法半导体推出的ARM Cortex-M3内核微控制器，主频72MHz，64KB Flash，20KB SRAM，支持SWD和JTAG调试。',
  datasheet: 'ICL4891JIM48561',
  images: [
    '/images/stm32-1.jpg',
    '/images/stm32-2.jpg',
    '/images/stm32-3.jpg',
    '/images/stm32-4.jpg'
  ],
  SellingPoint: 'Compression Fittings Have A Single Sleeve Which Bites into Tubing As You TightenThe Nut To Create A Strong Seal. Zinc-Plated Steel ls Strong And Has Fair Corrosion Resistance.',
  specifications: [
    { name: '内核', value: 'ARM Cortex-M3' },
    { name: '主频', value: '72MHz' },
    { name: 'Flash', value: '64KB' },
    { name: 'SRAM', value: '20KB' },
    { name: '工作电压', value: '2.0V - 3.6V' },
    { name: 'GPIO', value: '37个可重映射IO口' }
  ]
})

const errors = ref({
    Name: '',
    Email: '',
    Company: '',
    Country: '',
    Quantity: ''
})

// 当前选中的图片
const selectedImage = ref(product.value.images[0])
// 订单信息
const orderInfo = ref({
  Name: '',
  Email: '',
  Company: '',
  Country: '',
  Quantity: 1,
})


// 查看pdf
const handlePdf = () => {
  // window.open(`/product/file`, '_blank')
}

const fetchMfgDetail = async (params) => {
  try {
    const response = await $request.post('/api/v1/partno/partnodetailasync', {
      PID: params.PID,
      StandPartNo: params.StandPartNo,
      StandMFG: params.StandMFG
    })
    product.value = response.Data
    // 处理响应数据
  } catch (error) {
    console.error('Error fetching Mfg detail:', error)
  }
}
// 提交Rfq请求
const handleRfq = async() => {
  const params = {
    Name: orderInfo.value.Name,
    Company: orderInfo.value.Company,
    Country: orderInfo.value.Country,
    Email: orderInfo.value.Email,
    RFQForms: [
      {
        PartNo: product.value.MFGPartNo,
        MFG: product.value.MFG,
        Quantity: orderInfo.value.Quantity,
      }
    ]
  }
  console.log(params);

  try {
    const response = await $request.post('/api/v1/rfq/rfqsubmitasync', params)
    console.log('RFQ response:', response)
     // 提交成功后显示弹框
     showSuccessModal.value = true
  } catch (error) {
    console.error('Error sending RFQ:', error)
  }
}

const handleSubmit = () => {
    // 重置错误信息
    errors.value = {
      Name: '',
      Email: '',
      Company: '',
      Country: '',
      Quantity: ''
    }

    let isValid = true

    // 验证逻辑
    if (!orderInfo.value.Name.trim()) {
      errors.value.Name = 'Contact name is required'
      isValid = false
    }

    if (!orderInfo.value.Email.trim()) {
      errors.value.Email = 'Business email is required'
      isValid = false
    } else if (!validateEmail(orderInfo.value.Email)) {
      errors.value.Email = 'Please enter a valid email'
      isValid = false
    }

    if (!orderInfo.value.Company.trim()) {
      errors.value.Company = 'Company name is required'
      isValid = false
    }

    if (!orderInfo.value.Country.trim()) {
      errors.value.Country = 'Country is required'
      isValid = false
    }

    if (!orderInfo.value.Quantity || orderInfo.value.Quantity < 1) {
      errors.value.Quantity = 'Quantity must be at least 1'
      isValid = false
    }

    // 通过验证后提交
    if (isValid) {
      handleRfq()
    }
}

const validateEmail = (email) => {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return re.test(email)
}

// 弹框显示状态
const showSuccessModal = ref(false)

const AddRfqList = () => {
  rfq.setData({
    PartNo: product.value.MFGPartNo,
    MFG: product.value.MFG,
    Quantity: orderInfo.value.Quantity,
  })
  router.push({
    path: '/rfq',
  })
}

onMounted(() => {
  const {PID, StandPartNo, StandMFG} = route.query
    fetchMfgDetail({PID, StandPartNo, StandMFG})
})
</script>

<style scoped>
/* 样式 */
/* 弹框动画 */
.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}
</style>